package com.erpoa.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class PropertiesHelper implements ApplicationContextAware {

    private static Logger logger = LoggerFactory.getLogger(PropertiesHelper.class);

    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        PropertiesHelper.applicationContext = ctx;
    }

    public static Object getPropery(String key) {
        if (applicationContext == null) {
            logger.error("获取[" + key + "]失败,spring上下文未初始化完成.");
            throw new RuntimeException("spring上下文未初始化完成.");
        }

        try {
            PropertiesFactoryBean pfb = applicationContext.getBean(PropertiesFactoryBean.class);
            if (pfb != null)
                return pfb.getObject().get(key);
        } catch (Exception e) {
            logger.error("获取[" + key + "]失败", e);
        }
        return null;
    }
}
